//
//  NSString+category.m
//  MiYun360
//
//  Created by xiaoshunliang on 16/5/12.
//  Copyright © 2016年 AUNotBad. All rights reserved.
//

#import "NSString+category.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (category)
+ (NSString *)showTip:(NSArray *)messageArr {
    for (NSInteger i=0; i<messageArr.count; i++) {
        NSDictionary *dic = [messageArr safeObjectAtIndex:i];
        if ([NSString isBlankString:[dic objectForKey:dic.allKeys[0]]]) {
            return dic.allKeys[0];
        }
    }
    return @"ok";
}

+ (BOOL)isBlankString:(id)string{
    
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    return NO;
    
}
+ (NSString *)splicingHttpStr:(NSString *)str{
    if ([str containsString:@"http://"]) {
        return str;
    }else{
        return str = [NSString stringWithFormat:@"%@%@",HOST_URL,str];
    
    }
}
+ (NSString *)fromTimeStringToTime:(NSString *)timeString{
    if (timeString.length <= 0) {
        return @"";
    }
    NSString *str=[timeString substringToIndex:timeString.length-3];
    NSString*time = str;
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[time intValue]];
    NSString*confromTimespStr = [formatter stringFromDate:confromTimesp];
    return  confromTimespStr;
}
+ (NSString *)fromTimeStringToDayAndMonth:(NSString *)timeString{
    if (timeString.length <= 0) {
        return @"";
    }
    NSString *str=[timeString substringToIndex:timeString.length-3];
    NSString*time = str;
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"dd日-M月"];
    NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[time intValue]];
    NSString*confromTimespStr = [formatter stringFromDate:confromTimesp];
    return  confromTimespStr;
}

#pragma mark - 判断身份证 -

+ (BOOL)identityIsValid:(NSString *)str {
    
    if (str.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
    //  NSString *regex = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:str]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[str substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [str substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]|| ![idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }else {
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}


#pragma mark- 返回一字符串是多久之前：刚刚，5秒前，1分钟前，1小时前等等
+ (NSString*)timeAgoWithDate:(NSString*)date
{
    date=[NSString stringWithFormat:@"%@",date];
    if (date.length<=0) {
        return @"";
    }
    NSString *datrStr = [NSString stringWithFormat:@"%@",date];
    NSString*time  = @"";
    if (datrStr.length>11) {
     time =[datrStr substringToIndex:datrStr.length-3];

    }else{
   time =[datrStr substringToIndex:datrStr.length-0];

    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyy-MM-dd HH:mm:ss"];
    NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[time intValue]];
    
    double deltaSeconds = fabs([confromTimesp timeIntervalSinceDate:[NSDate date]]);
    double deltaMinutes = deltaSeconds / 60.0f;
    
    if (deltaSeconds < 5) {
        
        return @"刚刚";
        
    }else if (deltaSeconds < 60){
        
        return [NSString stringWithFormat:@"%d秒前",(int)ceil(deltaSeconds)];
        
    }else if (deltaMinutes < 60){
        
        return [NSString stringWithFormat:@"%d分钟前",(int)ceil(deltaMinutes)];
        
    }else if (deltaMinutes < (24 * 60)){
        
        int hour = floor(deltaMinutes/60);
        return [NSString stringWithFormat:@"%d小时前",hour];
        
    }else if (deltaMinutes < (24 * 60 * 7)){
        
        int day = (int)floor(deltaMinutes/(60 * 24));
        return [NSString stringWithFormat:@"%d天前",day];
        
    }else if (deltaMinutes < (24 * 60 * 31)){
        
        int week = (int)floor(deltaMinutes/(60 * 24 * 7));
        return [NSString stringWithFormat:@"%d周前",week];
        
    }else if (deltaMinutes < (24 * 60 * 365.25)){
        
        int month = (int)floor(deltaMinutes/(60 * 24 * 30));
        return [NSString stringWithFormat:@"%d个月前",month];
        
    }else{
        
        int year = (int)floor(deltaMinutes/(60 * 24 * 365));
        return [NSString stringWithFormat:@"%d年前",year];
    }
}

+ (CGFloat)heightWithWidth:(CGFloat)width font:(CGFloat)font text:(NSString *)text {
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size.height;
}
+ (CGFloat)heightWithWidth:(CGFloat)width fontNameString:(NSString *)fontName fontSize:(CGFloat)fontSize text:(NSString *)text {
    
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:fontSize*KFontScale]} context:nil].size;
    return size.height;
}


+ (CGFloat)widthWithFont:(CGFloat)font text:(NSString *)text {
    CGSize size = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil].size;
    return size.width;
}
+ (CGFloat)widthWithFont:(CGFloat)font fontNameString:(NSString *)fontName text:(NSString *)text {
    CGSize size = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:font*KFontScale]} context:nil].size;
    return size.width;
}

/**
 *  指定字体的大小返回size
 */
+ (CGSize)sizeWithFontSize:(CGFloat)fontSize text:(NSString *)text {
    
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:fontSize]}];
    return size;
}
/**
 *  指定行数的大小返回frame
 */
+ (CGFloat)boundsWithFontSize:(CGFloat)fontSize text:(NSString *)text needWidth:(CGFloat)needWidth lineNumber:(NSInteger)lineNumber{
    lineNumber =lineNumber+1;
    NSString *str = text;
    if (str.length<=0) {
        str= @"";
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 3;
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(needWidth,CGFLOAT_MAX ) options:options context:nil];
    
    if ((rect.size.height - font.lineHeight) <= style.lineSpacing) {
        if ([[self class] containChinese:str]) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-style.lineSpacing);
        }
    }
    CGFloat textHeight;
    if (lineNumber>1) {
        if (rect.size.height>lineNumber*font.lineHeight) {
            textHeight = lineNumber*font.lineHeight;
        }else{
            textHeight = rect.size.height;
        }
    }else{
        textHeight = rect.size.height;
    }
    return textHeight;
    
}
/**
 *  指定字体的大小返回frame
 */
+ (CGRect)boundsWithFontSize:(CGFloat)fontSize text:(NSString *)text needWidth:(CGFloat)needWidth {
    NSString *str = text;
    if (str.length<=0) {
        str= @"";
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 3;
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(needWidth, CGFLOAT_MAX) options:options context:nil];
    if ((rect.size.height - font.lineHeight) <= style.lineSpacing) {
        if ([[self class] containChinese:str]) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-style.lineSpacing);
        }
    }
    return rect;
}
//判断如果包含中文
+ (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
/**
 *  替换掉null的字符串
 *
 */
+ (NSString *)nullString:(NSString *)nullStr {
    
    if (nullStr == nil || nullStr == NULL) {
        return @"";
    }
    if ([nullStr isKindOfClass:[NSNull class]]) {
        return @"";
    }
    if (![nullStr isKindOfClass:[NSString class]]) {
        return @"";
    }
    if ([[nullStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return @"";
    }
    return nullStr;
}
/**
 *  判断是不是手机号
 */
- (BOOL)isValidMobileNumber
{
    static NSString *const regex = @"^(1)\\d{10}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:self];
}

/**
 *  用特定的格式显示当前时间
 */
+ (NSString *)setTheCurrentTimeWithFormat:(NSDate *)date fromat:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSString* timeStr = [formatter stringFromDate:date];
    return timeStr;
}
/**
 *  用当前时间 - 结束时间 来比较看是否答题已经结束 yes:结束 no:未结束
 */
+ (BOOL)isCurrentTimeCutEndTimeWithDate:(NSDate *)date endTime:(NSString*)endTimeStr {
    double timeInterval = [[NSDate date] timeIntervalSince1970];
    NSString *endTimeComplate = [NSString stringWithFormat:@"%.0f",[endTimeStr floatValue]/1000];
    int surplus = (timeInterval - [endTimeComplate integerValue]);
    NSLog(@"时间间隔问题====%f====%ld----字符串%@",timeInterval,(long)[endTimeStr integerValue],endTimeComplate);
    if (surplus < 0) {  //没有结束
        return NO;
    }
    return YES;
}

/**
 *  是不是中文
 */
- (BOOL)isChinese{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
- (NSString *)MD5 {
    if (self == nil || [self length] == 0)
        return nil;
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
    CC_MD5([self UTF8String], (int)[self lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
    NSMutableString *ms = [NSMutableString string];
    for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ms appendFormat:@"%02x", (int)(digest[i])];
    }
    return [ms copy];
}
+ (NSString *)MD5 {
    if (self == nil || [[self class] length] == 0)
        return nil;
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
    CC_MD5([[self class] UTF8String], (int)[[self class] lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
    NSMutableString *ms = [NSMutableString string];
    for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ms appendFormat:@"%02x", (int)(digest[i])];
    }
    return [ms copy];
}
+ (NSString *)encodeUrlStr:(NSString *)urlStr{
    NSString *encodedString = (NSString *)
    
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              
                                                              (CFStringRef)urlStr,
                                                              
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              
                                                              NULL,
                                                              
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
    
    
    
}
/*
 * 打印拼接好的url
 * @params params:传的参数
 * @params urlStr:请求的url
 */
+ (void)printAppendHttpURL:(NSDictionary *)params urlStr:(NSString *)urlStr{
    
    NSLog(@"此处请求的参数params====%@",params);
    NSArray *paramsArr = [params allKeys];
    NSString *paramsStr = @"";
    for (NSInteger i = 0; i < paramsArr.count; i++) {
        NSString *value = [params objectForKey:paramsArr[i]];
        paramsStr = [NSString stringWithFormat:@"%@&%@",paramsStr,[NSString stringWithFormat:@"%@=%@",paramsArr[i],value]];
    }
    NSString *urlString = [NSString stringWithFormat:@"%@%@",urlStr,paramsStr];
    NSLog(@"此处请求的url是：%@",urlString);
}
// 校验密码为8位数字和字母的组合格式
+ (BOOL)judgePassword:(NSString *)text{
    NSString * regex = @"^[0-9A-Za-z]{6,}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:text];
    if (isMatch) {
        return YES;
    }else{
        return NO;
    }
}
/**
 判断金额输入的是否符合要求
 @return YES 表示符合要求  反之不符合要求
 */
+ (BOOL)judgeCash:(NSString *)text{
    /**
     (1)0开头的以为数字 如:0.2
     (2)非0开头的最多9位数字
     (3)小数点后面最多两位数字
     @"^(\\d{0,9}|0)(\\.\\d{0,2})?$";
     */
    NSString *regex = @"^([1-9]\\d{0,9}|0)(\\.\\d{0,2})?$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:text];
    if (isMatch) {
        return YES;
    }else{
        return NO;
    }
}
@end

